# coding: utf-8
from typing import Union

from PySide6.QtCore import Qt, QUrl
from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineSettings
from qframelesswindow.webengine import FramelessWebEngineView

from .base import TopBaseInterface


class _WebEngineView(FramelessWebEngineView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True)
        self.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu)
        page = self.page()
        page.setDevToolsPage(page)

        self.settings().setAttribute(QWebEngineSettings.WebAttribute.PluginsEnabled, True)
        self.settings().setAttribute(QWebEngineSettings.WebAttribute.SpatialNavigationEnabled, True)

    def createWindow(self, type_: QWebEnginePage.WebWindowType):
        page = _WebEngineView(self)
        page.urlChanged.connect(self.load)
        return page


class WebEngineView(TopBaseInterface):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.web_view = _WebEngineView(self)
        self.setWidget(self.web_view)
        self.setViewportMargins(0, 45, 0, 0)

    def load(self, url: Union[str, QUrl]):
        self.web_view.load(QUrl(url))
